package com.zhou.common.mybatis.template.shiro.zhou.config.redis.cash;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.ConversionService;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.scheduling.annotation.Async;

/**
 * MyRedisCache
 *
 * @author zhouxianfeng
 * @date 2021-4-9
 */
@Slf4j
public class MyRedisCache extends RedisCache {

    private String myName;
    private RedisCacheWriter myCacheWriter;
    private RedisCacheConfiguration myCacheConfig;
    private ConversionService myConversionService;

    private Class classWihtMapKeyIsDate;

    private ObjectMapper objectMapper;


    /**
     * Create new {@link RedisCache}.
     *
     * @param name        must not be {@literal null}.
     * @param cacheWriter must not be {@literal null}.
     * @param cacheConfig must not be {@literal null}.
     */
    protected MyRedisCache(String name, RedisCacheWriter cacheWriter, RedisCacheConfiguration cacheConfig) {
        super(name, cacheWriter, cacheConfig);
        this.myName = name;
        this.myCacheWriter = cacheWriter;
        this.myCacheConfig = cacheConfig;
        this.myConversionService = cacheConfig.getConversionService();
    }

    @Async
    @Override
    public void evict(Object key) {
        if (key instanceof String && ((String) key).contains("*")) {// 通配符删除
            Long start = System.currentTimeMillis();
            byte[] pattern = this.myConversionService.convert(this.createCacheKey(key), byte[].class);
            this.myCacheWriter.clean(this.myName, pattern);
            long elapse = System.currentTimeMillis() - start;
            if (elapse > 600) {
                log.warn("剔除缓存耗时({})超过600ms,进行告警", elapse);
                //TODO 增加异步处理
            }
            log.info("剔除缓存耗时({}ms)", elapse);
        } else {// 单一key删除
            super.evict(key);
        }
    }

}
